package org.bim.view.drag.design.controller;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.bim.view.drag.design.constant.CommonConstant;
import org.springframework.cloud.gateway.mvc.ProxyExchange;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@Slf4j
public class ProxyController {
    @GetMapping("data/proxy")
    @PostMapping("data/proxy")
    public ResponseEntity<?> getProxy(ProxyExchange<byte[]> proxy,HttpServletRequest request){
        String targetUri = request.getParameter(CommonConstant.PROXY_HEADER_KEY);
        try {
            // build up the redirect URL
            long time = System.currentTimeMillis();
            log.info("调用远程地址开始：method: {}, url：{}", request.getMethod(), targetUri);
            ResponseEntity<?> result = proxyRequest(proxy.uri(targetUri), request.getMethod());
            log.info("调用远程地址结束：method: {}, url：{}", request.getMethod(), targetUri);
            log.info("调用远程地址结束：耗时：{}ms", System.currentTimeMillis() - time);
            return result;
        } catch (Exception e) {
            log.error("代理过程中出现异常，{}", e.getMessage());
            return new ResponseEntity<>(new JSONObject(), HttpStatus.OK);
        }
    }
    private static <T> ResponseEntity<T> proxyRequest(ProxyExchange<T> proxy, String method) {
        switch (method.toUpperCase()) {
            case "GET":
                return proxy.get();
            case "POST":
                return proxy.post();
            case "PUT":
                return proxy.put();
            case "PATCH":
                return proxy.patch();
            case "DELETE":
                return proxy.delete();
            case "HEAD":
                return proxy.head();
            case "OPTIONS":
                return proxy.options();
            default:
                throw new IllegalArgumentException("异常HTTP请求方法！");
        }
    }

}
